import subprocess
import time
from datetime import datetime, timedelta

class VoiceAlarmAutomatedTests:
    def __init__(self):
        self.package_name = "com.example.voicealarm"
        self.main_activity = "com.example.voicealarm.MainActivity"

    def execute_adb(self, command):
        """执行 ADB 命令"""
        try:
            result = subprocess.run(f"adb {command}", shell=True, capture_output=True, text=True)
            return result.stdout.strip()
        except Exception as e:
            print(f"ADB command failed: {e}")
            return None

    def start_app(self):
        """启动应用 - 用于多个测试用例"""
        return self.execute_adb(f"shell am start -n {self.package_name}/{self.main_activity}")

    def force_stop_app(self):
        """强制停止应用 - 用于测试重置"""
        return self.execute_adb(f"shell am force-stop {self.package_name}")

    def clear_app_data(self):
        """清除应用数据 - 用于测试重置"""
        return self.execute_adb(f"shell pm clear {self.package_name}")

    # TC001 - 创建基本闹钟
    def test_create_basic_alarm(self):
        """测试创建基本闹钟"""
        self.start_app()
        time.sleep(1)
        # 点击添加闹钟按钮
        self.execute_adb("shell input tap 950 150")  # 根据实际按钮位置调整坐标
        time.sleep(1)
        # 设置时间（模拟点击时间选择器）
        self.execute_adb("shell input tap 540 800")
        time.sleep(1)
        # 确认时间
        self.execute_adb("shell input tap 850 1200")
        # 验证闹钟是否创建
        alarm_list = self.execute_adb("shell dumpsys activity providers | grep -A 5 'com.example.voicealarm.provider'")
        return "Success" if alarm_list else "Fail"

    # TC004 - 编辑现有闹钟
    def test_edit_alarm(self):
        """测试编辑闹钟"""
        self.start_app()
        time.sleep(1)
        # 长按第一个闹钟项
        self.execute_adb("shell input touchscreen swipe 540 300 540 300 1000")
        time.sleep(1)
        # 修改时间
        self.execute_adb("shell input tap 540 800")
        time.sleep(1)
        # 确认修改
        self.execute_adb("shell input tap 850 1200")
        return "Success"

    # TC005 - 切换闹钟开关状态
    def test_toggle_alarm(self):
        """测试切换闹钟开关"""
        self.start_app()
        time.sleep(1)
        # 点击第一个闹钟的开关
        self.execute_adb("shell input tap 900 300")
        # 验证开关状态
        alarm_status = self.execute_adb("shell dumpsys activity providers | grep 'enabled'")
        return "Success" if alarm_status else "Fail"

    # TC006 - 删除闹钟
    def test_delete_alarm(self):
        """测试删除闹钟"""
        self.start_app()
        time.sleep(1)
        # 长按第一个闹钟项
        self.execute_adb("shell input touchscreen swipe 540 300 540 300 1000")
        time.sleep(1)
        # 点击删除按钮
        self.execute_adb("shell input tap 850 400")
        # 确认删除
        self.execute_adb("shell input tap 750 1200")
        return "Success"

    # TC015 - 闹钟列表显示
    def test_alarm_list_display(self):
        """测试闹钟列表显示"""
        self.start_app()
        time.sleep(1)
        # 获取当前显示的闹钟列表
        alarm_list = self.execute_adb("shell dumpsys activity providers | grep -A 10 'com.example.voicealarm.provider'")
        return "Success" if alarm_list else "Fail"

    # TC020 - 设备重启后闹钟持久化
    def test_alarm_persistence_after_reboot(self):
        """测试重启后闹钟持久化"""
        # 创建测试闹钟
        self.test_create_basic_alarm()
        time.sleep(1)
        # 记录当前闹钟状态
        before_reboot = self.execute_adb("shell dumpsys alarm | grep 'com.example.voicealarm'")
        # 重启设备
        self.execute_adb("shell reboot")
        time.sleep(60)  # 等待设备重启
        # 验证闹钟是否保持
        after_reboot = self.execute_adb("shell dumpsys alarm | grep 'com.example.voicealarm'")
        return "Success" if before_reboot == after_reboot else "Fail"

    # TC021 - 后台运行测试
    def test_background_operation(self):
        """测试应用后台运行"""
        self.test_create_basic_alarm()
        # 退出应用
        self.execute_adb("shell input keyevent KEYCODE_HOME")
        time.sleep(5)
        # 检查闹钟服务是否在运行
        service_status = self.execute_adb("shell dumpsys activity services | grep 'com.example.voicealarm.AlarmService'")
        return "Success" if service_status else "Fail"

    # TC022 - 低电量行为测试
    def test_low_battery_behavior(self):
        """测试低电量情况下的闹钟行为"""
        # 模拟低电量状态
        self.execute_adb("shell dumpsys battery set level 5")
        # 创建闹钟
        self.test_create_basic_alarm()
        # 检查闹钟是否正常设置
        alarm_status = self.execute_adb("shell dumpsys alarm | grep 'com.example.voicealarm'")
        # 恢复电池状态
        self.execute_adb("shell dumpsys battery reset")
        return "Success" if alarm_status else "Fail"

    # TC025 - 内存使用测试
    def test_memory_usage(self):
        """测试应用内存使用"""
        self.start_app()
        time.sleep(5)
        # 获取内存使用情况
        memory_info = self.execute_adb(f"shell dumpsys meminfo {self.package_name}")
        # 解析内存信息
        if memory_info:
            # 检查内存是否在合理范围内（例如小于100MB）
            return "Success" if "100000K" not in memory_info else "Fail"
        return "Fail"

    # TC027 - 最大闹钟数测试
    def test_maximum_alarms(self):
        """测试创建最大数量闹钟"""
        self.start_app()
        # 创建多个闹钟（例如50个）
        for i in range(50):
            self.test_create_basic_alarm()
            time.sleep(1)
        # 检查系统稳定性
        app_anr = self.execute_adb("shell dumpsys activity | grep ANR")
        return "Fail" if app_anr else "Success"

    def run_all_tests(self):
        """运行所有自动化测试"""
        tests = [
            ("TC001 - 创建基本闹钟", self.test_create_basic_alarm),
            ("TC004 - 编辑闹钟", self.test_edit_alarm),
            ("TC005 - 切换闹钟开关", self.test_toggle_alarm),
            ("TC006 - 删除闹钟", self.test_delete_alarm),
            ("TC015 - 闹钟列表显示", self.test_alarm_list_display),
            ("TC020 - 重启后闹钟持久化", self.test_alarm_persistence_after_reboot),
            ("TC021 - 后台运行", self.test_background_operation),
            ("TC022 - 低电量行为", self.test_low_battery_behavior),
            ("TC025 - 内存使用", self.test_memory_usage),
            ("TC027 - 最大闹钟数", self.test_maximum_alarms)
        ]

        print("开始运行自动化测试...")
        for test_name, test_func in tests:
            print(f"\n执行测试: {test_name}")
            try:
                result = test_func()
                print(f"测试结果: {result}")
            except Exception as e:
                print(f"测试失败: {e}")
            finally:
                # 重置应用状态
                self.force_stop_app()
                time.sleep(1)

if __name__ == "__main__":
    tests = VoiceAlarmAutomatedTests()
    tests.run_all_tests()
